// eslint-disable-next-line import/no-extraneous-dependencies
import { parse } from 'url';

// mock storeDataSource
const genList = (current, pageSize) => {
  const storeDataSource = [];

  for (let i = 0; i < pageSize; i += 1) {
    const index = (current - 1) * 10 + i;
    storeDataSource.push({
      key: index,
      storeName: `商户名称 ${index}`,
      introduce: `商户介绍 ${index}`,
      address: `地址 ${index}`,
      leader: `负责人 ${index}`,
      phone: `联系电话 ${index}`,
      communityIds:[1,2],
      communityNames:["小区1","小区2"],
      status: Math.floor(Math.random() * 10) % 2,
    });
  }

  storeDataSource.reverse();
  return storeDataSource;
};

let storeDataSource = genList(1, 100);

function getStore(req, res, u) {
  let realUrl = u;

  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query;
  let dataSource = [...storeDataSource].slice((current - 1) * pageSize, current * pageSize);

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }

      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(item => {
          if (parseInt(`${item.status}`, 10) === parseInt(s.split('')[0], 10)) {
            return true;
          }

          return false;
        }),
      );
    });
    dataSource = filterDataSource;
  }

  if (params.storeName) {
    dataSource = dataSource.filter(data => data.storeName.includes(params.storeName || ''));
  }

  const result = {
    data: dataSource,
    total: storeDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };
  return res.json(result);
}

function postStore(req, res, u, b) {
  let realUrl = u;

  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  const { method, storeName, introduce,address,leader,phone,communityIds,status, key } = body;

  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'delete':
      storeDataSource = storeDataSource.filter(item => key !== item.key);
      break;

    case 'post':
      (() => {
        const i = Math.ceil(Math.random() * 10000);
        const newStore = {
          key: storeDataSource.length,
          storeName, introduce,address,leader,phone,communityIds,status:1
        };
        storeDataSource.unshift(newStore);
        return res.json(newStore);
      })();

      return;

    case 'update':
      (() => {
        let newStore = {};
        storeDataSource = storeDataSource.map(item => {
          if (item.key === key) {
            newStore = { ...item, storeName, introduce,address,leader,phone,communityIds,status };
            return { ...item, storeName, introduce,address,leader,phone,communityIds,status };
          }

          return item;
        });
        return res.json(newStore);
      })();

      return;

    default:
      break;
  }

  const result = {
    list: storeDataSource,
    pagination: {
      total: storeDataSource.length,
    },
  };
  res.json(result);
}

function getCommunityList(){
  const communityList =[]
  for (let i = 0; i < 8; i += 1) {
    communityList.push({
      communityId: i+1,
      communityName: `小区 ${i+1}`,
    });
  }
  return communityList;
}

export default {
  'GET /api/store': getStore,
  'POST /api/store': postStore,
  'GET /api/community': {data:[
    {
      communityId: 1,
      communityName: '小区1',
    },
    {
      communityId: 2,
      communityName: '小区2',
    },
    {
      communityId: 3,
      communityName: '小区3',
    },
    {
      communityId: 4,
      communityName: '小区3',
    },
    {
      communityId: 5,
      communityName: '小区5',
    },
    {
      communityId: 6,
      communityName: '小区6',
    },
  ]},
};
